/*
  作者：不正经绣才
  日期：2025.8.26
*/
const { logInfo, logWarn, logError } = require('../../utils/log.js');
Page({
  data: {
    navHeight: 44, // 导航栏高度
    statusBarHeight: 20, // 状态栏高度
    capsuleButtonInfo: null, // 胶囊按钮信息
    wheels: [], // 存储用户创建的转盘
    hotWheels: [], // 热门转盘数据
    currentTab: 'my', // 当前选中的标签，默认"我的转盘"
    // 快速创建相关数据
    showQuickCreateModal: false,
    quickCreateInput: '',
    quickCreateItemCount: 0,
    // 闪电动画相关数据
    lightningAnimation: false,
    triggerLightning: false
  },

  onLoad() {
    // 清理无效的历史记录
    this.cleanInvalidHistory();
    
    this.loadWheels();
    this.loadHotWheels(); // 加载热门转盘数据
    
    // 启动闪电动画
    this.startLightningAnimation();
  },

  onShow() {
    // 页面切换时重新加载数据
    logInfo('转盘列表页面onShow - 开始刷新数据');
    
    // 清理无效的历史记录
    this.cleanInvalidHistory();
    
    // 重新加载我的转盘列表
    this.loadWheels();
    
    // 重新加载热门转盘列表
    this.loadHotWheels();
    
    // 如果当前显示的是我的转盘标签，确保数据是最新的
    if (this.data.currentTab === 'my') {
      logInfo('当前在我的转盘标签，额外刷新一次');
      // 可以在这里添加额外的刷新逻辑
    }
    
    logInfo('转盘列表页面onShow - 刷新完成');
  },

  // 处理导航栏高度变化事件
  onNavHeightChange: function(e) {
    const navHeight = e.detail.navHeight;
    const statusBarHeight = e.detail.statusBarHeight;
    const capsuleButtonInfo = e.detail.capsuleButtonInfo;
    
    this.setData({
      navHeight: navHeight,
      statusBarHeight: statusBarHeight,
      capsuleButtonInfo: capsuleButtonInfo
    });
  },

  // 启动闪电动画
  startLightningAnimation() {
    this.setData({
      lightningAnimation: true
    });
  },

  // 显示快速创建弹窗
  showQuickCreateModal() {
    // 触发闪电动画
    this.setData({ 
      triggerLightning: true,
      showQuickCreateModal: true,
      quickCreateInput: '',
      quickCreateItemCount: 0
    });
    
    // 300ms后重置动画触发状态
    setTimeout(() => {
      this.setData({
        triggerLightning: false
      });
    }, 300);
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // 加载我的转盘列表
  loadWheels() {
    // 从本地存储获取转盘数据
    try {
      const wheels = wx.getStorageSync('wheels') || [];
      // 为每个转盘添加统计信息
      const wheelsWithStats = wheels.map(wheel => {
        return this.addStatsToWheel(wheel);
      });
      this.setData({ wheels: wheelsWithStats });
    } catch (e) {
      logError('加载转盘数据失败', e);
    }
  },

  // 为转盘添加统计信息
  addStatsToWheel(wheel) {
    // 获取使用统计
    const stats = this.getWheelStats(wheel.id);
    const lastUsedId = wx.getStorageSync('lastUsedWheelId');
    
    return {
      ...wheel,
      usageCount: stats.usageCount,
      lastUsedTime: stats.lastUsedTime,
      lastUsed: lastUsedId === wheel.id
    };
  },

  // 获取转盘使用统计信息
  getWheelStats(wheelId) {
    try {
      // 从两个历史记录源中统计使用次数
      const wheelHistory = wx.getStorageSync('wheelHistory') || [];
      const gameHistory = wx.getStorageSync('gameHistory') || [];
      
      // 检查并清理无效的历史记录
      this.cleanInvalidHistory();
      
      // 从转盘专用历史记录中获取数据
      const wheelSpecificHistory = wheelHistory.filter(item => item.wheelId === wheelId);
      
      // 从通用工具历史中获取转盘相关数据（作为备用）
      const currentWheelName = this.getCurrentWheelName(wheelId);
      const gameWheelHistory = gameHistory.filter(item => 
        item.mode === 'wheel' && 
        currentWheelName && 
        (item.name === currentWheelName || item.name.includes(currentWheelName))
      );
      
      // 优先使用转盘专用历史，如果为空则使用工具历史作为备用
      const combinedHistory = wheelSpecificHistory.length > 0 
        ? wheelSpecificHistory 
        : gameWheelHistory.map(item => ({
            wheelId: wheelId,
            wheelName: item.name,
            result: item.result,
            time: this.convertGameHistoryTime(item.time)
          }));
      
      let usageCount = combinedHistory.length;
      let lastUsedTime = null;
      
      if (combinedHistory.length > 0) {
        // 按时间排序得到最近使用时间
        const sortedHistory = combinedHistory.sort((a, b) => new Date(b.time) - new Date(a.time));
        lastUsedTime = this.formatTime(sortedHistory[0].time);
      }
      
      return {
        usageCount,
        lastUsedTime
      };
    } catch (e) {
      logError('获取转盘统计失败', e);
      return {
        usageCount: 0,
        lastUsedTime: null
      };
    }
  },

  // 获取当前转盘名称（用于匹配工具历史）
  getCurrentWheelName(wheelId) {
    try {
      const wheels = wx.getStorageSync('wheels') || [];
      const wheel = wheels.find(w => w.id === wheelId);
      return wheel ? wheel.name : null;
    } catch (e) {
      logError('获取转盘名称失败', e);
      return null;
    }
  },

  // 转换工具历史时间格式
  convertGameHistoryTime(timeString) {
    try {
      // 尝试解析中文时间格式
      const date = new Date(timeString);
      if (isNaN(date.getTime())) {
        // 如果解析失败，返回当前时间
        return new Date().toISOString();
      }
      return date.toISOString();
    } catch (e) {
      return new Date().toISOString();
    }
  },

  // 清理无效的历史记录（已删除转盘的记录）
  cleanInvalidHistory() {
    try {
      const wheels = wx.getStorageSync('wheels') || [];
      const validWheelIds = wheels.map(w => w.id);
      
      // 清理转盘专用历史记录
      const wheelHistory = wx.getStorageSync('wheelHistory') || [];
      const validWheelHistory = wheelHistory.filter(item => 
        item.wheelId && validWheelIds.includes(item.wheelId)
      );
      
      if (validWheelHistory.length !== wheelHistory.length) {
        wx.setStorageSync('wheelHistory', validWheelHistory);
        logInfo(`清理了 ${wheelHistory.length - validWheelHistory.length} 条无效的转盘历史记录`);
      }
      
    } catch (e) {
      logError('清理无效历史记录失败', e);
    }
  },

  // 格式化时间显示
  formatTime(timeString) {
    if (!timeString) return null;
    
    try {
      let time;
      
      // 尝试解析不同格式的时间字符串
      if (timeString.includes('T') && timeString.includes('Z')) {
        // ISO 8601 格式
        time = new Date(timeString);
      } else if (timeString.includes('/') || timeString.includes('-')) {
        // 本地化时间格式
        time = new Date(timeString);
      } else {
        // 其他格式，直接尝试解析
        time = new Date(timeString);
      }
      
      // 检查时间是否有效
      if (isNaN(time.getTime())) {
        logError('无效的时间格式:', timeString);
        return '时间解析错误';
      }
      
      const now = new Date();
      const diff = now - time;
      
      // 计算时间差
      const minutes = Math.floor(diff / (1000 * 60));
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (minutes < 1) {
        return '刚刚';
      } else if (minutes < 60) {
        return `${minutes}分钟前`;
      } else if (hours < 24) {
        return `${hours}小时前`;
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        // 超过一周显示具体日期
        return time.toLocaleDateString('zh-CN', {
          month: 'short',
          day: 'numeric'
        });
      }
    } catch (e) {
      logError('格式化时间失败', e, '时间字符串:', timeString);
      return '时间错误';
    }
  },

  // 加载热门转盘列表
  loadHotWheels() {
    // 热门转盘示例数据
    const hotWheels = [
      {
        id: 'hot1',
        name: '早餐吃什么',
        items: [
          { text: '牛奶🥛', color: '#ff7675', weight: 1 },
          { text: '面包🥖', color: '#74b9ff', weight: 1 },
          { text: '三明治🥪', color: '#55efc4', weight: 1 },
          { text: '培根🥓', color: '#ffeaa7', weight: 1 },
          { text: '香肠🌭', color: '#a29bfe', weight: 1 },
          { text: '煎蛋🍳', color: '#fd79a8', weight: 1 },
          { text: '粥品🥣', color: '#fdcb6e', weight: 1 },
          { text: '薄煎饼🥞', color: '#00cec9', weight: 1 },
          { text: '苹果🍎', color: '#ff7675', weight: 1 },
          { text: '香蕉🍌', color: '#74b9ff', weight: 1 }
        ],
      },
      {
        id: 'hot2',
        name: '午餐吃什么',
        items: [
          { text: '盒饭🍱', color: '#ff7675', weight: 1 },
          { text: '米饭🍚', color: '#74b9ff', weight: 1 },
          { text: '咖喱饭🍛', color: '#55efc4', weight: 1 },
          { text: '面条🍜', color: '#ffeaa7', weight: 1 },
          { text: '意大利面🍝', color: '#a29bfe', weight: 1 },
          { text: '汉堡包🍔', color: '#fd79a8', weight: 1 },
          { text: '薯条🍟', color: '#fdcb6e', weight: 1 },
          { text: '披萨🍕', color: '#00cec9', weight: 1 },
          { text: '火锅🍲', color: '#ff7675', weight: 1 },
          { text: '墨西哥卷饼🌮', color: '#74b9ff', weight: 1 },
          { text: '玉米煎饼🌯', color: '#55efc4', weight: 1 },
          { text: '三明治🥪', color: '#ffeaa7', weight: 1 },
          { text: '寿司🍣', color: '#a29bfe', weight: 1 },
          { text: '炸虾🍤', color: '#fd79a8', weight: 1 },
          { text: '沙拉🥗', color: '#fdcb6e', weight: 1 }
        ],
      },
      {
        id: 'hot3',
        name: '晚餐吃什么',
        items: [
          { text: '🍝意大利面', color: '#ff7675', weight: 1 },
          { text: '🍔汉堡', color: '#74b9ff', weight: 1 },
          { text: '🍟薯条', color: '#55efc4', weight: 1 },
          { text: '🍕披萨', color: '#ffeaa7', weight: 1 },
          { text: '🍛咖喱饭', color: '#a29bfe', weight: 1 },
          { text: '🥩肉块', color: '#fd79a8', weight: 1 },
          { text: '🍗鸡腿', color: '#fdcb6e', weight: 1 },
          { text: '🥪三明治', color: '#00cec9', weight: 1 },
          { text: '🍲火锅', color: '#ff7675', weight: 1 }
        ],
      },
      {
        id: 'hot4',
        name: '周末干啥',
        items: [
          { text: '去露营🏕️', color: '#ff7675', weight: 1 },
          { text: '做早餐🍳', color: '#74b9ff', weight: 1 },
          { text: '读书📚', color: '#55efc4', weight: 1 },
          { text: '画画🎨', color: '#ffeaa7', weight: 1 },
          { text: '骑自行车🚴', color: '#a29bfe', weight: 1 },
          { text: '游泳🏊', color: '#fd79a8', weight: 1 },
          { text: '看电影🎬', color: '#fdcb6e', weight: 1 },
          { text: '聚会👭', color: '#00cec9', weight: 1 },
          { text: '健身锻炼🏋️‍', color: '#ff7675', weight: 1 },
          { text: '整理房间🧺', color: '#74b9ff', weight: 1 }
        ],
      },
      {
        id: 'hot5',
        name: '运动选择',
        items: [
          { text: '足球⚽', color: '#ff7675', weight: 1 },
          { text: '篮球🏀', color: '#74b9ff', weight: 1 },
          { text: '乒乓球🏓', color: '#55efc4', weight: 1 },
          { text: '羽毛球🏸', color: '#ffeaa7', weight: 1 },
          { text: '冰球🏒', color: '#a29bfe', weight: 1 },
          { text: '高尔夫球🏌️', color: '#fd79a8', weight: 1 },
          { text: '垒球🥎', color: '#fdcb6e', weight: 1 },
          { text: '射箭🏹', color: '#00cec9', weight: 1 },
          { text: '‍拳击🥊', color: '#ff7675', weight: 1 },
          { text: '游泳🏊', color: '#74b9ff', weight: 1 },
          { text: '骑自行车🚴', color: '#55efc4', weight: 1 },
          { text: '瑜伽🧘', color: '#ffeaa7', weight: 1 },
        ],
      },
      {
        id: 'hot6',
        name: '水果选择',
        items: [
          { text: '红苹果🍎', color: '#ff7675', weight: 1 },
          { text: '青苹果🍏', color: '#74b9ff', weight: 1 },
          { text: '梨🍐', color: '#55efc4', weight: 1 },
          { text: '桃子🍑', color: '#ffeaa7', weight: 1 },
          { text: '樱桃🍒', color: '#a29bfe', weight: 1 },
          { text: '草莓🍓', color: '#fd79a8', weight: 1 },
		      { text: '葡萄🍇', color: '#fdcb6e', weight: 1 },
          { text: '甜瓜🍈', color: '#00cec9', weight: 1 },
		      { text: '西瓜🍉', color: '#ff7675', weight: 1 },
          { text: '橘子🍊', color: '#74b9ff', weight: 1 },
          { text: '柠檬🍋', color: '#55efc4', weight: 1 },
          { text: '香蕉🍌', color: '#ffeaa7', weight: 1 },
          { text: '菠萝🍍', color: '#a29bfe', weight: 1 },
          { text: '芒果🥭', color: '#fd79a8', weight: 1 },
		      { text: '异果🥝', color: '#fdcb6e', weight: 1 },
          { text: '西红柿🍅', color: '#00cec9', weight: 1 },
		      { text: '橄榄🫒', color: '#ff7675', weight: 1 },
          { text: '椰子🥥', color: '#74b9ff', weight: 1 },
          { text: '牛油果🥑', color: '#55efc4', weight: 1 },
          { text: '蓝莓🫐', color: '#ffeaa7', weight: 1 }
        ],
      },
    ];
    
    this.setData({ hotWheels });
  },

  // 创建新转盘
  createNewWheel() {
    wx.navigateTo({
      url: '/pages/edit-wheel/edit-wheel'
    });
  },

  // 显示快速创建弹窗
  showQuickCreateModal() {
    this.setData({ 
      showQuickCreateModal: true,
      quickCreateInput: '',
      quickCreateItemCount: 0
    });
  },

  // 隐藏快速创建弹窗
  hideQuickCreateModal() {
    this.setData({ showQuickCreateModal: false });
  },

  // 处理快速创建输入框内容变化
  onQuickCreateInputChange(e) {
    let quickCreateInput = e.detail.value;
    // 计算项目数量（使用逗号分割，同时处理可能的中文逗号）
    const normalizedInput = quickCreateInput.replace(/，/g, ','); // 将中文逗号替换为英文逗号
    const quickCreateItemCount = normalizedInput.trim() ? 
      normalizedInput.trim().split(',').filter(item => item.trim()).length : 0;
    
    this.setData({ 
      quickCreateInput: normalizedInput, // 保存标准化后的输入
      quickCreateItemCount
    });
  },

  // 处理快速创建逻辑
  handleQuickCreate() {
    let { quickCreateInput } = this.data;
    if (!quickCreateInput.trim()) {
      wx.showToast({
        title: '请输入转盘项目',
        icon: 'none'
      });
      return;
    }

    // 标准化输入（处理中文逗号）
    quickCreateInput = quickCreateInput.replace(/，/g, ',');
    
    // 1. 按逗号拆分输入内容
    const items = quickCreateInput.trim().split(',').filter(item => item.trim() !== '');
    if (items.length === 0) {
      wx.showToast({
        title: '请输入有效项目内容',
        icon: 'none'
      });
      return;
    }
    
    // 检查项目数量限制（最多20个）
    if (items.length > 20) {
      wx.showToast({
        title: '最多只能创建20个项目',
        icon: 'none'
      });
      return;
    }

    // 2. 定义颜色选项（与编辑页面保持一致）
    const colorOptions = [
      '#ff7675',
      '#74b9ff',
      '#55efc4',
      '#ffeaa7',
      '#a29bfe',
      '#fd79a8',
      '#fdcb6e',
      '#00cec9',
    ];

    // 3. 解析每个项目内容，创建项目
    const validItems = [];
    for (let i = 0; i < items.length; i++) {
      const item = items[i].trim();
      const text = item.trim();
      
      // 验证项目名称不能为空
      if (!text) {
        wx.showToast({
          title: `第${i+1}项：项目名称不能为空`,
          icon: 'none',
          duration: 1500
        });
        return;
      }
      
      // 验证项目名称长度不能超过10个字
      if (text.length > 10) {
        wx.showToast({
          title: `第${i+1}项：项目名称不能超过10个字`,
          icon: 'none',
          duration: 1500
        });
        return;
      }

      // 按顺序取色（循环使用颜色）
      const currentColor = colorOptions[i % colorOptions.length];
      validItems.push({
        text: text,
        color: currentColor,
        weight: 1 // 默认权重为1
      });
    }

    // 4. 检查转盘数量限制
    const wheels = wx.getStorageSync('wheels') || [];
    if (wheels.length >= 20) {
      wx.showToast({
        title: '最多只能创建20个转盘',
        icon: 'none'
      });
      return;
    }

    // 5. 生成转盘名称（递增数字）
    const wheelNames = wheels.map(wheel => wheel.name);
    let wheelNumber = 1;
    let wheelName = `转盘${wheelNumber}`;
    while (wheelNames.includes(wheelName)) {
      wheelNumber++;
      wheelName = `转盘${wheelNumber}`;
    }

    // 6. 创建转盘
    const newWheel = {
      id: Date.now().toString(),
      name: wheelName,
      items: validItems
    };

    // 7. 保存转盘
    try {
      wheels.push(newWheel);
      wx.setStorageSync('wheels', wheels);
      
      // 更新全局变量 allWheels
      const app = getApp();
      app.globalData.allWheels = wheels;
      
      // 更新页面数据
      this.setData({
        wheels: wheels.map(w => this.addStatsToWheel(w)),
        showQuickCreateModal: false
      });

      wx.showToast({
        title: '创建成功',
        icon: 'success'
      });
    } catch (e) {
      logError('保存转盘失败', e);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 选择我的转盘
  selectWheel(e) {
    const id = e.currentTarget.dataset.id;
    const wheel = this.data.wheels.find(w => w.id === id);
    
    if (wheel) {
      const app = getApp();
      app.globalData.currentWheel = wheel;

      // 保存最后使用的转盘ID到本地存储
      try {
        wx.setStorageSync('lastUsedWheelId', id);
      } catch (e) {
        logError('保存lastUsedWheelId失败', e);
      }
      
      wx.showToast({
        title: '已选择转盘',
        icon: 'success'
      });
      
      // 返回首页
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  // 选择热门转盘
  selectHotWheel(e) {
    const id = e.currentTarget.dataset.id;
    const wheel = this.data.hotWheels.find(w => w.id === id);
    
    if (wheel) {
      const app = getApp();
      
      // 准备更新数据
      let allWheels = app.globalData.allWheels || [];
      
      // 检查是否已存在同名转盘，如果存在则删除旧的
      const existingIndex = allWheels.findIndex(w => w.name === wheel.name);
      if (existingIndex !== -1) {
        // 删除旧的同名转盘
        allWheels.splice(existingIndex, 1);
        logInfo(`删除已存在的同名转盘：${wheel.name}`);
      }

      // 复制热门转盘数据并生成新ID，避免修改源数据
      const newWheel = {
        ...wheel,
        id: Date.now().toString(), // 生成新的唯一ID
        isHot: false, // 标记为非热门，因为这是用户选择的副本
        usageCount: 0, // 初始化使用次数
        lastUsedTime: null, // 初始化最后使用时间
        lastUsed: false // 初始化最后使用状态
      };
      
      // 添加新的热门转盘到我的转盘中
      allWheels.push(newWheel);
      
      // 更新全局数据
      app.globalData.allWheels = allWheels;
      
      try {
        // 先更新本地存储
        wx.setStorageSync('wheels', allWheels);
        // 刷新当前页面的我的转盘列表
        this.setData({
          wheels: allWheels.map(w => this.addStatsToWheel(w))
        });
        
        // 保存最后使用的转盘ID
        wx.setStorageSync('lastUsedWheelId', newWheel.id);
        app.globalData.currentWheel = newWheel;
        
        wx.showToast({
          title: '已选择热门转盘',
          icon: 'success',
          duration: 500, // 显示0.5秒后再跳转
          success: () => {
            // 延迟跳转，确保用户能看到提示并完成列表刷新
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }, 1000);
          }
        });
      } catch (e) {
        logError('处理热门转盘失败', e);
      }
    }
  },

  // 编辑转盘（保持不变）
  editWheel(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/edit-wheel/edit-wheel?id=${id}`
    });
  },

  // 删除转盘（保证至少保留一个转盘）
  deleteWheel(e) {
    const id = e.currentTarget.dataset.id;
    const app = getApp(); // 获取全局实例
    logInfo('删除当前转盘', id);

    // 检查是否为最后一个转盘
    if (this.data.wheels.length <= 1) {
      wx.showToast({
        title: '至少保留一个转盘',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个转盘吗？',
      success: (res) => {
        if (res.confirm) {
          const wheels = this.data.wheels.filter(w => w.id !== id);
          
          try {
            // 更新本地存储和全局数据
            const wheelsData = wheels.map(w => {
              // 移除统计信息，只保存原始转盘数据
              const { usageCount, lastUsedTime, lastUsed, ...wheelData } = w;
              return wheelData;
            });
            
            wx.setStorageSync('wheels', wheelsData);
            this.setData({ wheels });

            // 更新全局变量 allWheels
            app.globalData.allWheels = wheelsData;

            // 检查删除的是否是最后使用的转盘，如果是则清除记录
            const lastUsedId = wx.getStorageSync('lastUsedWheelId');
            if (lastUsedId === id) {
              wx.removeStorageSync('lastUsedWheelId');
              // 如果删除的是当前使用的转盘，则清空全局当前转盘
              app.globalData.currentWheel = null;
            }

            // 清理该转盘的历史记录
            this.cleanWheelHistory(id);

            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } catch (e) {
            logError('删除转盘失败', e);
          }
        }
      }
    });
  },

  // 清理转盘历史记录
  cleanWheelHistory(wheelId) {
    try {
      const history = wx.getStorageSync('wheelHistory') || [];
      const filteredHistory = history.filter(item => item.wheelId !== wheelId);
      wx.setStorageSync('wheelHistory', filteredHistory);
      logInfo(`已清理转盘 ${wheelId} 的历史记录`);
    } catch (e) {
      logError('清理历史记录失败', e);
    }
  },
  
  // 配置分享给好友
  onShareAppMessage() {
    return {
      title: '小幸运转盘',
      path: '/pages/my/my',
      imageUrl: '',
      success: (res) => {
        wx.showToast({
          title: '分享成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail: (res) => {
        wx.showToast({
          title: '分享失败',
          icon: 'none',
          duration: 1000
        });
      }
    }
  },
  
  // 配置分享到朋友圈
  onShareTimeline() {
    return {
      title: '小幸运转盘',
      query: 'page=my',
      imageUrl: ''
    }
  },

  // 广告日志打印
  adLoad() {
    logInfo('原生模板广告加载成功')
  },

  adError(err) {
    logError('原生模板广告加载失败', err)
  },

  adClose() {
    logInfo('原生模板广告关闭')
  },
});